package dht.run;

import java.net.InetAddress;

import dht.IServer;
import dht.entity.GlobalVariables;
import dht.entity.NodeInfo;
import dht.server.DataServerImpl;
import dse.IOUtil;
import dse.modules.eln.EarthLikeNetwork;
import dse.modules.eln.NodeWithCoordinates;

public class DataServer {

	public void runDataServer(String configFile) throws Exception {

		GlobalVariables.initialize(configFile);

		NodeInfo localInfo = new NodeInfo();
		localInfo.setIp(InetAddress.getLocalHost().getHostAddress());
		localInfo.setPort(GlobalVariables.localPort);

		EarthLikeNetwork network = IOUtil
				.NetworkFromFile(GlobalVariables.networkFile);
		int nodeId = Math.abs(localInfo.hashCode()) % network.maxNodeId() + 1;
		localInfo.setX(((NodeWithCoordinates) network.lookupNode(nodeId))
				.getX());
		localInfo.setY(((NodeWithCoordinates) network.lookupNode(nodeId))
				.getY());

		NodeInfo masterInfo = new NodeInfo();
		masterInfo.setIp(InetAddress.getByName(GlobalVariables.masterIp)
				.getHostAddress());
		masterInfo.setPort(GlobalVariables.masterPort);

		nodeId = Math.abs(masterInfo.hashCode()) % network.maxNodeId() + 1;
		masterInfo.setX(((NodeWithCoordinates) network.lookupNode(nodeId))
				.getX());
		masterInfo.setY(((NodeWithCoordinates) network.lookupNode(nodeId))
				.getY());

		IServer dataServer = new DataServerImpl(localInfo, masterInfo);
		dataServer.startServer();
	}

	public static void main(String args[]) throws Exception {
		DataServer ds = new DataServer();
		ds.runDataServer(args[0]);
	}
}
